package PathHelper

import (
	"errors"
	"io"
	"io/fs"
	"io/ioutil"
	"os"
	"path"
)

func MkDirs(pathStr string) (string , error){
	dir := path.Dir(pathStr)
	if len(dir) == 0 {
		return "", errors.New("dir can not empty")
	}
	_, err := os.Stat(dir)
	if err !=nil && !os.IsNotExist(err){
		return "", err
	}
	err = os.MkdirAll(dir, 0777)
	if err != nil {
		return "", err
	}
	return dir, nil
}

/**
保存文件
 */
func SaveFile(filePath string, src io.Reader) (*os.File, error) {
	_, err := MkDirs(filePath)
	if err!=nil{
		return nil,err
	}
	f, err:=os.Create(filePath)
	if err !=nil{
		return nil, err
	}
	defer f.Close()
	_, err = io.Copy(f, src)
	if err!=nil{
		return nil,err
	}
	return f, nil
}

/**
复制文件
 */
func CopyFile(src , dist string, perm fs.FileMode) error {
	input, err:= ioutil.ReadFile(src)
	if err !=nil{
		return err
	}
	err = ioutil.WriteFile(dist, input, perm)
	if err !=nil{
		return err
	}
	return nil
}